import os
import os.path
import scipy.ndimage
import scipy.misc
from celery import Celery
app = Celery('tasks', broker='redis://localhost:6379/0', backend='redis://localhost')


@app.task
def pre_pocess(file_name, output_name):
    try:
        img = scipy.misc.imread(file_name)
        if output_name.find('.') < 0:
            output_name += '.png'
        # crop file
        left, right = 0, img.shape[1] - 1
        top, bottom = 0, img.shape[0] - 1

        while True:
            s = img[:, left, 1].sum() / img.shape[1]
            if s > 5:
                break
            left += 5
        while True:
            s = img[:, right, 1].sum() / img.shape[1]
            if s > 5:
                break
            right -= 5
        while True:
            s = img[top, :, 1].sum() / img.shape[0]
            if s > 5:
                break
            top += 5
        while True:
            s = img[bottom, :, 1].sum() / img.shape[0]
            if s > 5:
                break
            bottom -= 5
        img = img[top:bottom, left:right, :]


        zoom_factor = [
            300 / img.shape[0],
            300 / img.shape[1],
            1
        ]
        zoomed = scipy.ndimage.zoom(img, zoom_factor, mode='nearest')
        scipy.misc.imsave(output_name, zoomed)
        return output_name
    except Exception as e:
        print(file_name, e)
        return ''


